package com.huika.sharpsdklib;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;

import com.mob.tools.utils.DeviceHelper;
import com.mob.tools.utils.UIHandler;

import java.io.File;
import java.io.FileOutputStream;

import static com.mob.tools.utils.BitmapHelper.captureView;

/**
 * Author: Victor Wu <br/>
 * Email: victor-wu*foxmail.com <br/>
 * Time: 2015/12/2 13:17 <br/>
 * Description: TODO
 */
public class Utils {

    public static String saveViewToImage(View view) throws Throwable {
        Bitmap bm = captureView(view, view.getWidth(), view.getHeight());
        return saveViewToImage(view.getContext(), bm);
    }

    public static String saveViewToImage(Context context, Bitmap viewBm) throws Throwable {
        if(viewBm != null && !viewBm.isRecycled()) {
            String path = getCachePath(context, "screenshot");
            File ss = new File(path, System.currentTimeMillis() + ".jpg");
            FileOutputStream fos = new FileOutputStream(ss);
            viewBm.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            return ss.getAbsolutePath();
        } else {
            return null;
        }
    }

    public static String getCachePath(Context context, String category) {
        String appDir = context.getFilesDir().getAbsolutePath() + "/DealOnTop/";
        DeviceHelper helper = DeviceHelper.getInstance(context);
        if(helper.getSdcardState()) {
            appDir = helper.getSdcardPath() + "/DealOnTop/";
        }

        if(!TextUtils.isEmpty(category)) {
            appDir = appDir + category + "/";
        }

        File file = new File(appDir);
        if(!file.exists()) {
            file.mkdirs();
        }

        return appDir;
    }
}
